package  
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.getTimer;
	/**
	 * ...
	 * @author UWGameDevClub
	 */
	public class Time extends Sprite
	{
		private var _startTime:Number;
		private var _duration:Number;
		
		private var _function:Function;
		
		private var _time:TextField;
		private var _format:TextFormat;
		
		public function Time(x:Number, y:Number, w:Number, h:Number) 
		{
			this.x = x;
			this.y = y;
			
			graphics.beginFill(0xbbbbcb, 0.75);
			graphics.drawRect(0, 0, w, h);
			graphics.endFill();
			
			//create the text field to display remaining time before the timer ends.
			_time = new TextField();
			_time.x = 0; _time.y = 0;
			_time.width = w; _time.height = h;
			_time.selectable = false;
			_time.text = "0:00";
			addChild(_time);
			
			_format = new TextFormat();
			_format.align = "center";
			_format.size = 18;
			_format.font = "Calibri";
			_time.setTextFormat(_format);
			
			visible = false;
		}
		
		public function start(duration:Number, fun:Function):void {
			_duration = duration * 1000;
			_startTime = getTimer();
			_function = fun;
			visible = true;
			
			addEventListener(Event.ENTER_FRAME, update);
		}
		
		public function cancel():void {
			removeEventListener(Event.ENTER_FRAME, update);
			visible = false;
		}
		
		private function update(event:Event):void {
			var remainingTime:Number = _duration - (getTimer() - _startTime);
			
			var seconds:int = remainingTime / 1000;
			var minutes:int = seconds / 60;
			seconds %= 60;
			
			_time.text = minutes + ":";
			if (seconds < 10) _time.appendText("0");
			_time.appendText(seconds.toString());
			_time.setTextFormat(_format);
			
			if (remainingTime <= 0) {
				if(_function != null) _function();
				removeEventListener(Event.ENTER_FRAME, update);
				visible = false;
			}
		}
		
	}

}